package global

import (
	"database/sql"
	"fmt"
	"github.com/Shopify/sarama"
	"github.com/go-redis/redis/v8"
	"github.com/songzhibin97/gkit/cache/local_cache"
	"github.com/spf13/viper"
	clientv3 "go.etcd.io/etcd/client/v3"
	"go.uber.org/zap"
	"golang.org/x/sync/singleflight"
	"gorm.io/gorm"
	"server/config"
	xcanal "server/dbtools/xcanal/canal"
	"server/utils/timer"
	"sync"
)

var (
	XidwViper  *viper.Viper
	XidwConfig config.Server

	SysDB *gorm.DB
	OdsDB *sql.DB
	UdsDB *sql.DB

	SqlDBList = make(map[string]*sql.DB)
	XidwRedis *redis.Client

	Logger    *zap.Logger
	XidwTimer = timer.NewTimerTask()
	CanalList = make(map[string]*xcanal.Canal)

	JobRunning = make(map[string]any)
	JobStart   = make(map[string]any)

	KafkaProducerList = make(map[string]*sarama.AsyncProducer)
	KafkaConsumerList = make(map[string]*sarama.Consumer)

	Etcd *clientv3.Client

	XidwSingleflight = &singleflight.Group{}

	XidwCache local_cache.Cache

	XidwLock sync.RWMutex
)

func GetOdsDB() *sql.DB {
	XidwLock.RLock()
	defer XidwLock.RUnlock()
	sqlDB := SqlDBList["ODS-DB"]
	if sqlDB != nil {
		return sqlDB
	}
	sqlDBYaml := XidwConfig.OdsDB
	conn, err := sqlDBYaml.SqlDB()
	if conn != nil && err == nil {
		if err := conn.Ping(); err != nil {
			Logger.Info(fmt.Sprintf("数据库连接测试ping失败:%v", err))
			return nil
		}
		SqlDBList["ODS-DB"] = conn
		return conn
	}
	Logger.Info(fmt.Sprintf("数据库连接测试open失败:%v", err))
	return nil
}

func GetUdsDB() *sql.DB {
	XidwLock.RLock()
	defer XidwLock.RUnlock()
	sqlDB := SqlDBList["UDS-DB"]
	if sqlDB != nil {
		return sqlDB
	}

	sqlDBYaml := XidwConfig.UdsDB
	conn, err := sqlDBYaml.SqlDB()
	if conn != nil && err == nil {
		if err := conn.Ping(); err != nil {
			Logger.Info(fmt.Sprintf("数据库连接测试ping失败:%v", err))
			return nil
		}
		SqlDBList["UDS-DB"] = conn
		return conn
	}
	Logger.Info(fmt.Sprintf("数据库连接测试open失败:%v", err))
	return nil
}
